<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>添加企业</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" :model="addForm" :rules="rules" label-width="100px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                /></el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                action="#"
                :limit="1"
                :before-remove="beforeRemove"
                :http-request="uploadRequest"
                :before-upload="beforeUpload"
              >
                <img v-if="addForm.businessLicenseUrl" class="business-img" :src="addForm.businessLicenseUrl" alt="">
                <el-button v-else size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.png .jpg .jpeg，文件大小不得超过5M</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="doSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { createRequiredRule } from '@/utils/validate'
import {
  getIndustryListAPI,
  addParkEnterpriseAPI,
  getParkEnterpriseDetailAPI,
  updateParkEnterpriseAPI
} from '@/api/enterprise'
import { uploadFile } from '@/api/common'

export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      // 校验规则
      rules: {
        name: [createRequiredRule('企业名称为必填')],
        legalPerson: [createRequiredRule('法人为必填')],
        registeredAddress: [createRequiredRule('注册地址为必填')],
        industryCode: [createRequiredRule('所在行业为必填', 'change')],
        contact: [createRequiredRule('企业联系人为必填')],
        contactNumber: [createRequiredRule('企业联系人电话为必填')],
        businessLicenseId: [createRequiredRule('请上传营业执照')]
      },
      // 行业数据
      // [{ industryCode: number, industryName: string }]
      industryList: []
    }
  },
  async created() {
    // 初始化时获取行业数据
    this.getIndustryData()

    // 编辑状态
    this.id = this.$route.query.id
    this.isEdit = !!this.id
    if (!this.isEdit) return
    // 如果是编辑状态，则获取企业详情，回显数据
    const res = await getParkEnterpriseDetailAPI(this.id)
    // 回填数据到表单
    // 修复：企业详情会包含很多无用字段，需要剔除
    Object.keys(this.addForm).forEach(key => {
      this.addForm[key] = res.data[key]
    })
    // 补充一个id字段，编辑接口必须要有这个字段
    this.addForm.id = this.id
  },
  methods: {
    // 获取行业信息
    async getIndustryData() {
      const res = await getIndustryListAPI()
      this.industryList = res.data
    },
    // 提交表单
    doSubmit() {
      const fn = this.isEdit ? updateParkEnterpriseAPI : addParkEnterpriseAPI
      // 手动校验
      this.$refs.ruleForm.validate()
        .then(() => {
          return fn(this.addForm)
        })
        .then(() => {
          // 提示用户，并返回上一页
          this.$message.success('操作成功')
          this.$router.back()
        })
        .catch(() => {})
    },
    // 上传前的校验，返回 true: 校验成功，允许上传，false: 校验失败，阻止上传
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 1

      if (!allowImgType) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传合同图片大小不能超过 1MB!')
        return false
      }
      return true
    },
    // 执行手动上传的方法
    async uploadRequest(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      // 上传类型，1、企业营业执照businessLicense 2、租赁合同附件contract
      formData.append('type', 'businessLicense')
      // 开始上传前显示一个加载中，给用户提示
      const loading = this.$loading({
        lock: true,
        text: '正在上传，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      })
      // 最长 10 秒后关闭loading
      const timer = setTimeout(() => {
        loading.close()
      }, 10 * 1000)
      // 开始上传
      const res = await uploadFile(formData)
      // 上传成功后主动关闭 loading ，并关闭定时器
      loading.close()
      clearTimeout(timer)
      // res 是上传结果
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url
    },
    // 删除上传文件前的回调钩子
    beforeRemove(obj) {
      // console.log(obj)
      // 删除比较复杂：
      // 1. 后台要删
      // 2. 前台也要删
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .business-img {
    width: 150px;
  }

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
